package cn.yh.register.hosp.service.impl;

import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.hosp.repository.DepartmentRepository;
import cn.yh.register.hosp.repository.HospitalRepository;
import cn.yh.register.hosp.repository.ScheduleRepository;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.BookingRule;
import cn.yh.register.model.hosp.Department;
import cn.yh.register.model.hosp.Hospital;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.hosp.BookingScheduleRuleVo;
import cn.yh.register.vo.hosp.ScheduleOrderVo;
import cn.yh.register.vo.hosp.ScheduleQueryVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    ScheduleRepository scheduleRepository;
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    DepartmentRepository departmentRepository;


    /**
     * 保存排班
     *
     * @param objectMap 排班信息
     */
    @Override
    public void saveSchedule(Map<String, Object> objectMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(objectMap), Schedule.class);
        Schedule sch = scheduleRepository.findByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (sch != null) {
            //修改
            schedule.setId(sch.getId());
            schedule.setCreateTime(sch.getCreateTime());
            schedule.setIsDeleted(sch.getIsDeleted());
        } else {
            //新增
            schedule.setCreateTime(new Date());
            schedule.setIsDeleted(0);

        }
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 分页查询排班列表
     *
     * @param page    当前页
     * @param size    每页条数
     * @param queryVo 查询条件
     * @return 分页数据
     */
    @Override
    public Page<Schedule> findBypage(Integer page, Integer size, ScheduleQueryVo queryVo) {
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(queryVo, schedule);
        schedule.setIsDeleted(0);
        //构造条件对象 Example
        Example<Schedule> example = Example.of(schedule, ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true));
        //Sort
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //pageRequest
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        //分页查询
        return scheduleRepository.findAll(example, pageRequest);

    }

    /**
     * 删除排班
     *
     * @param hoscode       医院编号
     * @param hosScheduleId 排班编号
     */
    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule sch = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (sch != null) {
            scheduleRepository.delete(sch);
        }

    }

    /**
     * 排班数据
     *
     * @param page    当前页
     * @param size    每页条数
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return 排班数据
     */
    @Override
    public Map<String, Object> getRuleSchedule(Integer page, Integer size, String hoscode, String depcode) {
        //查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //定义聚合查询的操作
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),//查询条件
                Aggregation.group("workDate")//按workDate分组
                        .first("workDate").as("workDate")//分组后第一条数据
                        .count().as("docCount")//分组后的排班数量就是医生数量
                        .sum("reservedNumber").as("reservedNumber")//当天可预约总数
                        .sum("availableNumber").as("availableNumber"), //当天剩余可预约总数
                Aggregation.sort(Sort.Direction.ASC, "workDate"),//按时间升序排列
                Aggregation.skip((page - 1) * size),
                Aggregation.limit(size)
        );

        /**
         * 执行聚合操作
         * 参数 1：聚合操作对象
         * 参数 2：数据库对应的实体类型
         * 参数 3：聚合操作后数据封装的类型 
         */
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //取出数据列表
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggResults.getMappedResults();
        // 获取条件查询分组后的总记录数
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria), // 查询条件
                Aggregation.group("workDate")); // 按workDate分组
        List<BookingScheduleRuleVo> mappedResults = mongoTemplate
                .aggregate(agg, Schedule.class, BookingScheduleRuleVo.class).getMappedResults();
        // 分组后列表的长度就是排班日期的总记录数
        int total = mappedResults.size();
        // 将日期转为周几
        for (BookingScheduleRuleVo ruleVo : scheduleRuleVoList) {
            String dayOfWeek = this.getDayOfWeek(new DateTime(ruleVo.getWorkDate()));
            ruleVo.setDayOfWeek(dayOfWeek);
        }
        // 组装Map返回
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("bookingScheduleRuleList", scheduleRuleVoList);
        // 获取医院名称
        String hosName = hospitalRepository.findByHoscode(hoscode).getHosname();
        // 其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * 查询某天的排班详情
     *
     * @param hoscode  医院编号
     * @param depcode  科室编号
     * @param workDate 排班日期
     * @return 当天的排班日期
     */
    @Override
    public List<Schedule> getScheduleDatail(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList = scheduleRepository
                .findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        return scheduleList;
    }

    /**
     * 排班数据
     *
     * @param page    当前页
     * @param size    每页条数
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return 排班数据
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer size, String hoscode, String depcode) {
        //获取医院信息
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        if (hospital == null) {
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        //获取日期分页数据
        IPage<Date> dateIPage = this.getDateList(page, size, bookingRule);
        //获取当前页的日期列表
        List<Date> dateList = dateIPage.getRecords();
        //查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);        //按日期分组统计排班数据
        // 定义聚合操作
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),    //匹配条件
                Aggregation.group("workDate")//按workDate分组
                       .first("workDate").as("workDate")//分组后第一条数据
                       .count().as("docCount")//分组后的排班数量就是医生数量
                       .sum("reservedNumber").as("reservedNumber")//当天可预约总数
                       .sum("availableNumber").as("availableNumber") //当天剩余可预约总数

        );
        //执行聚合操作 获取分组后排班数据列表
        List<BookingScheduleRuleVo> scheduleRuleVoList = mongoTemplate
                .aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class)
                .getMappedResults();
        // 将list 转为Map
        // key :排班日期 value : 这一天的排班数据
        Map<Date, BookingScheduleRuleVo> ruleVoMap = scheduleRuleVoList.stream().collect(Collectors.toMap(
                BookingScheduleRuleVo::getWorkDate,//排班日期
                BookingScheduleRuleVo -> BookingScheduleRuleVo));//这一天的排班数据
        //获取可预约的日期对应的排班数据
        List<BookingScheduleRuleVo> ruleVoList =new ArrayList<>();
        for (int i = 0,len = dateList.size()-1; i<dateList.size(); i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo scheduleRuleVo = ruleVoMap.get(date);
            if (scheduleRuleVo == null) {
                // 说明当天没有排班医生
                scheduleRuleVo = new BookingScheduleRuleVo();
                // 就诊医生人数
                scheduleRuleVo.setDocCount(0);
                // 可预约数
                scheduleRuleVo.setReservedNumber(0);
                // 科室剩余预约数  -1表示无号
                scheduleRuleVo.setAvailableNumber(-1);
            }
            scheduleRuleVo.setWorkDate(date);
            scheduleRuleVo.setWorkDateMd(date);
            scheduleRuleVo.setStatus(0);//状态 0：正常 1：即将放号 -1：当天已停止挂号

            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            scheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (page == dateIPage.getPages() && i == len)  {
                scheduleRuleVo.setStatus(1);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                //停挂时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    scheduleRuleVo.setStatus(-1);
                }
            }
            ruleVoList.add(scheduleRuleVo);
        }
        //组装map返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleList", ruleVoList);
        result.put("total", dateIPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalRepository.findByHoscode(hoscode).getHosname());
        //科室
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;

    }

    /**
     * 查询排班详情
     *
     * @param id 排班id
     * @return 排班详情
     */
    @Override
    public Schedule getById(String id) {
        Optional<Schedule> optional = scheduleRepository.findById(id);
        Schedule schedule =null;
        if (optional.isPresent()) {
            schedule = optional.get();
            // 根据医院编号查询医院信息   医院名字
            schedule.getParam().put("hosname",hospitalRepository.findByHoscode(schedule.getHoscode()).getHosname());
            // 根据医院编号&科室编号查询科室信息  科室名称
            schedule.getParam().put("depname",departmentRepository
                    .findByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        }
        return schedule;
    }

    /**
     * 获取预约下单需要的排班数据
     * @param scheduleId 排班id
     * @return 预约下单需要的排班数据
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //根据id 查询排班数据
        Schedule schedule = this.getById(scheduleId);
        if (schedule==null){
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        //医院信息
        Hospital hospital = hospitalRepository.findByHoscode(schedule.getHoscode());
        if (hospital == null) {
             throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        //预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        //组装ScheduleOrderVo对象返回
        ScheduleOrderVo scheduleOrderVo=new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(hospital.getHoscode());//医院编号
        scheduleOrderVo.setHosname(hospital.getHosname());//医院名称
        Department department = departmentRepository.findByHoscodeAndDepcode(hospital.getHoscode(), schedule.getDepcode());
        scheduleOrderVo.setDepcode(department.getDepcode());//科室编号
        scheduleOrderVo.setDepname(department.getDepname());//科室名称
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());//医院排班表的主键id
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());//剩余预约数
        scheduleOrderVo.setTitle(schedule.getTitle());//医生职称
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());//安排日期
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());//安排时间（0：上午 1：下午）
        scheduleOrderVo.setAmount(schedule.getAmount());//医事服务费
        // 退号时间
        DateTime quitTime = this.getDateTime(
                new DateTime(schedule.getWorkDate()).plusDays(bookingRule.getQuitDay()).toDate(),
                bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        // 预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        // 预约结束时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(),
                bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        // 当天停挂时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    /**
     * 更新号源
     * @param schedule 排班对象
     */
    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);

    }

    /**
     * 根据医院排班主键获取排班信息
     *
     * @param hosScheduleId 医院的排班主键
     * @return 排班信息
     */
    @Override
    public Schedule getSchedule(String hosScheduleId) {
        return scheduleRepository.findByHosScheduleId(hosScheduleId);

    }

    /**
     * 获取可预约的日期列表
     * @param bookingRule 预约规则
     * @return 可以约的日期列表
     */
    private IPage<Date> getDateList(Integer page, Integer size, BookingRule bookingRule) {
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //停挂时间 HH:mm  格式要转为 yyyy-MM-dd HH-mm
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        //如果当前时间已经过了停挂时间 则预约周期+1 最后一天显示即将放号
        if (stopTime.isBeforeNow()) {
            cycle += 1;
        }
        //根据预约周期推算日期列表
        List<Date> dateList = new ArrayList<>();

        for (int i = 0; i < cycle; i++) {
            //只要日期 yyyy-MM-dd
            String dateTimeStr = new DateTime().plusDays(i).toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateTimeStr).toDate());
        }
        //分页起始位置
        int start = (page - 1) * size;
        int end = start + size;
        //如果end超过集合长度 给 end 从是新赋值
        if (end > dateList.size()) {
            end = dateList.size();
        }

        //组装当前页日期数据
        List<Date> pageDateList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));

        }
        //组装page对象返回
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7,dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 将String类型的时间(格式：HH:mm) 转换为DateTime类型（格式：yyyy-MM-dd HH:mm）
     *
     * @param date       日期（年月日）
     * @param timeString 时间字符串（时分）
     * @return 年月日时分（yyyy-MM-dd HH:mm）
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    /**
     * 根据日期获取周几数据
     *
     * @param dateTime 日期
     * @return 周几
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
